package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.DataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 设备信息Service业务层处理
 *
 * @author JQ
 * @date 2025-08-04
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 批量插入设备数据
     *
     * @param data
     */
    @Override
    public void batchInsert(IotMsgNotifyData data) {
        //1.设备数据
        //1.1根据设备ID获取设备信息 device_id
        String deviceId=data.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, deviceId));
        if(device==null){
            return;
        }
        //2.上报数据
        List<DeviceData> list=new ArrayList<>();
        //2.1遍历services
        data.getBody().getServices().forEach(s->{
            //处理上报时间日期
            LocalDateTime eventTime= LocalDateTimeUtil.parse(s.getEventTime(),"yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //properties中的每个属性都需要封装成DeviceData
            s.getProperties().forEach((k,v)->{
                DeviceData deviceData =  BeanUtil.toBean(device,DeviceData.class);
                deviceData.setFunctionId(k);
                deviceData.setId(null);
                deviceData.setDataValue(v.toString());
                deviceData.setCreateTime(new Date());
                deviceData.setAlarmTime(alarmTime);
                list.add(deviceData);
            });
        });


        //3.批量新增
        saveBatch(list);

        //存储到redis
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId, JSONUtil.toJsonStr(list));
    }


    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param dto 设备信息
     * @return 设备信息
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto) {
        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        // 模糊查询 设备名称
        if (StringUtils.isNotEmpty(dto.getDeviceName())){
            lambdaQueryWrapper.eq(DeviceData::getDeviceName, dto.getDeviceName());
        }
        // 模糊查询 功能名称
        if (StringUtils.isNotEmpty(dto.getFunctionId())){
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        // 时间范围查询
        if (ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime())) {
            lambdaQueryWrapper.between(DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());
        }
        page = page(page, lambdaQueryWrapper);

        // 构造 tableDataInfo
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return tableDataInfo;
    }

    /**
     * 新增设备信息
     *
     * @param deviceData 设备信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        deviceData.setCreateTime(DateUtils.getNowDate());
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备信息
     *
     * @param deviceData 设备信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        deviceData.setUpdateTime(DateUtils.getNowDate());
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 查询设备健康数据列表(按周)
     *
     * @param iotId 设备ID
     * @param functionId 功能ID
     * @param endTime 结束时间
     * @param startTime 开始时间
     * @return 设备数据列表
     */
    @Override
    public List<DataVo> queryDeviceDataListByWeek(String iotId, String functionId, Long endTime, Long startTime) {
        LocalDateTime startT = LocalDateTimeUtil.of(startTime);
        LocalDateTime endT = LocalDateTimeUtil.of(endTime);

        LocalDateTime begin=startT;
        LocalDateTime end=begin.plusDays(1L);
        List<DataVo> list=new ArrayList<>();
        while(begin.isBefore(endT)){
            boolean flag=false;
            List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, begin, end)
                    .orderByAsc(DeviceData::getAlarmTime));
            DataVo vo=new DataVo();
            Double sum=0d;
            int size=0;
            LocalDateTime alarmTime=null;
            for (DeviceData deviceData : deviceDataList) {
                alarmTime = deviceData.getAlarmTime();
                if(!flag &&alarmTime.isBefore(end)&&alarmTime.isAfter(begin)){
                    sum=sum+Double.parseDouble(deviceData.getDataValue());
                    size++;
                    flag=true;
                }
            }
            vo.setDateTime(alarmTime);
            Double avg=sum/size;
            // 将浮点数转换为整数
            vo.setDataValue((double) Math.round(avg));
            list.add(vo);
            begin=begin.plusDays(1L);
            end=end.plusDays(1L);
        }
        return list;
    }


    /**
     * 查询设备健康数据列表(按天)
     *
     * @param iotId 设备ID
     * @param functionId 功能ID
     * @param endTime 结束时间
     * @param startTime 开始时间
     * @return 设备数据列表
     */
    @Override
    public List<DataVo> queryDeviceDataListByDay(String iotId, String functionId, Long endTime, Long startTime) {
        LocalDateTime startT = LocalDateTimeUtil.of(startTime);
        LocalDateTime endT = LocalDateTimeUtil.of(endTime);

        LocalDateTime begin=startT;
        LocalDateTime end=begin.plusHours(1L);
        List<DataVo> list=new ArrayList<>();
        while(begin.isBefore(endT)){
            DeviceData deviceData = deviceDataMapper.selectOne(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, begin, end)
                    .orderByAsc(DeviceData::getAlarmTime)
                    .last("limit 1"));
            DataVo vo=new DataVo();
            vo.setDateTime(begin);
            if(ObjectUtil.isNotEmpty(deviceData) && ObjectUtil.isNotEmpty(deviceData.getDataValue())){
                // 将浮点数转换为整数
                vo.setDataValue((double) Math.round(Double.parseDouble(deviceData.getDataValue())));
            }else{
                // 如果当前小时没有数据，则查找最近的数据点
                DeviceData latestData = deviceDataMapper.selectOne(Wrappers.<DeviceData>lambdaQuery()
                        .eq(DeviceData::getIotId, iotId)
                        .eq(DeviceData::getFunctionId, functionId)
                        .lt(DeviceData::getAlarmTime, begin)
                        .orderByDesc(DeviceData::getAlarmTime)
                        .last("limit 1"));

                if(ObjectUtil.isNotEmpty(latestData) && ObjectUtil.isNotEmpty(latestData.getDataValue())){
                    // 将浮点数转换为整数
                    vo.setDataValue((double) Math.round(Double.parseDouble(latestData.getDataValue())));
                }else{
                    vo.setDataValue(0d);
                }
            }
            list.add(vo);
            begin=begin.plusHours(1L);
            end=end.plusHours(1L);
        }
        return list;

    }

}
